#include "mainwidget.h"
#include "mashwelder.h"
#include "PlasticPresses/plasticpresses.h"
#include "PunchingMachine/punchingmachine.h"
#include "ProductionOrder/productionlistview.h"
#include "Setting/BasicSetting/basicsettingwidget.h"
#include "dataview/productionorderlistmodel.h"
#include <QJsonDocument>
#include "lock_dlg.h"

bool MainWidget::_QCCheckPass = false;
bool MainWidget::_FirstCheckPass = false;
bool MainWidget::_hasModule =  false;
MainWidget::MainWidget(MainWindow *parent) :
    QWidget(parent),
    m_usbPortName({"","","",""}),
    m_productionOrderManagement(NULL),
    m_deviceState(DeviceState::getObj()),
    m_spotCheckDialog(NULL),
    m_qcCheckDialog(NULL),
    m_spotChekDelayTimer(new QTimer(0)),
    m_deviceInfo(new DeviceInfo),
    m_currentStation(""),
    order_doing_id(0),
    order_finished_flag(false),
    m_materialBarcodeScanFlag(false),
    m_qcCheck_circleAskTimer(NULL),
    m_qc_checkTimer(new QTimer(0)),
    materialCheckDialog(NULL),
    m_productListView(NULL),
    tProductionInfo({"","","","","","","","","","","",""}),
    m_spotDelayTimer(new QTimer(0)),
    m_qc_checkDelayTimer(new QTimer(0)),
    m_currentProductName(""),
    m_currentWorkNum(""),
    m_currentWorkStartTime(""),
    m_currentTaskId(""),
    m_scaleCom(NULL)

{
    mParent = parent;
    initDevice();
    initSome();
    getUsbPortName();
    connect(this,                       SIGNAL(materialConfirm_signals()),      this,                       SLOT(materialConfirm_slots()));
    connect(this,                       SIGNAL(startFirstProduction()),         this,                       SLOT(startFirstProduction_slots()));
    connect(this,                       SIGNAL(hanjieguifanNum(ProductionVariant)),         this,           SLOT(slot_hanjieguifanhao(ProductionVariant)));

    connect(this,    SIGNAL(sig_orderCompleted()), this, SLOT(slot_send7data()));
    connect(this,    SIGNAL(sig_orderCompleted()), this, SLOT(slot_clearOrderMsg()));
    connect(mParent  , SIGNAL(sendOperator(QString, QString,  DeviceState::DeviceStion)) ,  this,   SLOT( slot_sendOperator(QString,QString,  DeviceState::DeviceStion))  );
    connect(mParent  , SIGNAL(sendQC(QString, QString,  DeviceState::DeviceStion)),  this,   SLOT( slot_sendOperator(QString,QString,  DeviceState::DeviceStion))  );
    connect(mParent  , SIGNAL(sendFirstCheck(QString, QString,  DeviceState::DeviceStion)) ,  this,   SLOT( slot_sendOperator(QString,QString,  DeviceState::DeviceStion))  );
    connect(mParent  , SIGNAL(sendMainTain(QString, QString,  DeviceState::DeviceStion)) ,  this,   SLOT( slot_sendOperator(QString,QString,  DeviceState::DeviceStion))  );


    connect(mParent  , SIGNAL(sendMaterial(QString, QString, QString )) ,    this,          SLOT( slot_sendMaterial(QString,QString, QString))  );
    connect(mParent  , SIGNAL(sendGongZhang(QString, QString )) ,    this,          SLOT( slot_sendGongZhang(QString, QString  ) ) );


}

MainWidget::~MainWidget()
{
    if(mHttpServer) {
        delete mHttpServer;
    }
}

void MainWidget::spotCheckDelay_Tips()
{
    if (m_spotChekDelayTimer) {
        if (m_spotChekDelayTimer->isActive()) {
            m_spotChekDelayTimer->stop();
        }
    }
    if (m_spotCheckDialog) {
        m_spotCheckDialog->close();
        delete m_spotCheckDialog;
        m_spotCheckDialog = NULL;
        QString tips = "点检超时，请重试～！";
        static MyMessageDialog *dialog = NULL;
        if(dialog == NULL) {
            dialog = new MyMessageDialog(tips,tr("警告"),this,tr("否"),tr("确定"));
        }

        if(dialog->exec() == QDialog::Accepted) {
            if (dialog) {
                dialog = NULL;
            }
            if (m_spotChekDelayTimer) {
                if (!m_spotChekDelayTimer->isActive()) {
                    m_spotChekDelayTimer->start();
                }
            }

            initSpotCheckDialogParama();
        }
        else {
            if (m_spotChekDelayTimer) {
                if (!m_spotChekDelayTimer->isActive()) {
                    m_spotChekDelayTimer->start();
                }
            }
            if (dialog) {
                dialog = NULL;
            }
        }
    }
}

void MainWidget::showDeviceCheckTips()
{
    if (m_spotCheckDialog) {
        m_spotCheckDialog->close();
        m_spotCheckDialog = NULL;
        deleteSpotScrollText();//TODO need test
        QString tips = "点检确认通过!";
        /*----zhanglong*/
        MashWelder::m_systemStatus &= 0xbfff;
        PunchingMachine::m_systemStatus &= 0xbfff;
        PlasticPresses::m_systemStatus &= 0xbfff;
        MashWelder::Equipment_ckeck = false;
        PunchingMachine::Equipment_ckeck = false;
        PlasticPresses::Equipment_ckeck = false;
        MyMessageDialog::message(this,
                                 "点检信息！",
                                 tips,
                                 1200);
    }
}

void MainWidget::showQCCheckTips()
{
    if (m_qcCheckDialog) {
        m_qcCheckDialog->close();
        m_qcCheckDialog = NULL;
        QString tips = "QC巡检确认通过!";
        /*----zhanglong*/
        MashWelder::m_systemStatus &= 0xbfff;
        PunchingMachine::m_systemStatus &= 0xbfff;
        PlasticPresses::m_systemStatus &= 0xbfff;
        MashWelder::QC_Scan_ckeck = false;
        PunchingMachine::QC_Scan_ckeck = false;
        PlasticPresses::QC_Scan_ckeck = false;
        MyMessageDialog::message(this,
                                 "QC巡检信息！",
                                 tips,
                                 1200);
    }
}

void MainWidget::testConfirmMaterial()
{
    emit materialConfirm_signals();
    m_productListView->quit();
}

void MainWidget::getUsbPortName()
{
    ReadUsbPort::getobj()->getUsbPortName(m_usbPortName);
}

void MainWidget::showProductionOrder()
{    
    ProductionOrderListModel::getModel()->selectTabel();
    if(m_productListView == NULL)
    {
        m_productListView = new ProductionListView(this,mParent->mainLayout(),BasicSettingWidget::MASHWELDER_MODE);
    }
    else
    {
        delete m_productListView;
        m_productListView = NULL;
        m_productListView = new ProductionListView(this,mParent->mainLayout(),BasicSettingWidget::MASHWELDER_MODE);
    }

    m_productListView->setVisible(true);
    connect(m_productListView,      SIGNAL(postConfirmOrderSignals()),          this,               SLOT(postOrder()));
    disconnect(this,                SIGNAL(showOrderTips()),                    m_productListView,  SLOT(showOrderCheckTips())); //TODO 20180729 remove for test
    connect(this,                   SIGNAL(showOrderTips()),                    m_productListView,  SLOT(showOrderCheckTips()));
    connect(this,                   SIGNAL(opreatorCheckOK_signals()),          m_productListView,  SIGNAL(operatorCheckOK_signals())); //TODO 20180726 remove for test
    connect(m_productListView,      SIGNAL(materialConfirm_FromlistView()),     this,               SLOT(testConfirmMaterial()));
    connect(m_productListView,      SIGNAL(enableOrderConfirm()),               m_productListView,  SLOT(enableOrderCheck_Slots()));
    connect(m_productListView,      SIGNAL(confirmCurrentOrder_FromDetaiInfo(ProductionVariant)),
            this,       SLOT(confirmCurrentOrderInfoByPostWay(ProductionVariant)));
    connect(m_productListView,      SIGNAL(quitSignal()),                       this,  SLOT(returnFromProductOrderList()));
}

void MainWidget::deleleMashWarningDialog()
{

}

void MainWidget::initHttpServer()
{
    mHttpServer = new HttpServer(this);
    mHttpServer->listen(QHostAddress::Any,4000);
    connect(mHttpServer,SIGNAL(dataSend(QByteArray,QByteArray)),this,SLOT(receiveHttpClientData(QByteArray,QByteArray)));

}



void MainWidget::saveProductionVariant(QJsonObject &obj, ProductionVariant &productInfo)
{
    if(obj.contains("TaskId")) {
        productInfo.TaskId = obj.value("TaskId").toString();
    }
    if(obj.contains("ProductName")) {
        productInfo.ProductName =QString::fromUtf8(( obj.value("ProductName").toString() ).toUtf8().data());
    }
    if(obj.contains("ProductCode")) {
        productInfo.ProductCode = obj.value("ProductCode").toString();
    }
    if(obj.contains("Mtype3")) {
        productInfo.Mtype3 = obj.value("Mtype3").toString();
    }
    if(obj.contains("DeviceType")) {
        productInfo.DeviceType = obj.value("DeviceType").toString();
    }
    if(obj.contains("OrderCode")) {
        productInfo.OrderCode = obj.value("OrderCode").toString();
    }
    if(obj.contains("WorkNum")) {
        productInfo.WorkNum = obj.value("WorkNum").toString();
    }
    if(obj.contains("WorkTime"))
    {
        productInfo.WorkTime = obj.value("WorkTime").toString();
    }
    if(obj.contains("ModuleId"))
    {
        if( obj.value("ModuleId").toArray().size() > 0)
            productInfo.ModuleId =  QString( QJsonDocument( obj.value("ModuleId").toArray()).toJson() );
        else
            productInfo.ModuleId = QString("");
    }
    if(obj.contains("DeviceId"))
    {
        productInfo.DeviceId = obj.value("DeviceId").toString();
    }
    if(obj.contains("ProcessId"))
    {
        productInfo.ProcessId = QString::number(obj.value("ProcessId").toInt() );
    }
    if(obj.contains("ToolingRatio"))
    {
        productInfo.ToolingRatio = QString::number(obj.value("ToolingRatio").toInt());
    }

    //解析MBOM
    QJsonArray  mbomArray = obj.value("MBOM").toArray();//json数组
    QString mbomJsonString = "";
    mbomJsonString.append("[");

    if(!mbomArray.isEmpty())
    {
        int size = mbomArray.size();
        for (int i =0; i < size; i++) {
            QJsonValue value = mbomArray.at(i);
            if (value.isObject())
            {
                mbomJsonString.append("{");
                mbomJsonString.append("\"ProjId\":");
                QString projId = value.toObject().value("ProjId").toString();
                mbomJsonString.append("\"");
                mbomJsonString.append(projId);
                mbomJsonString.append("\"");
                mbomJsonString.append(",");
                mbomJsonString.append("\"MCode\":");
                QString mcode = value.toObject().value("MCode").toString();
                mbomJsonString.append("\"");
                mbomJsonString.append(mcode);
                mbomJsonString.append("\"");
                mbomJsonString.append(",");
                mbomJsonString.append("\"Mnum\":");
                int mnum = value.toObject().value("Mnum").toInt();
                mbomJsonString.append(QString::number(mnum));
                mbomJsonString.append("}");
            }
            mbomJsonString.append(",");
        }
    }
    mbomJsonString = mbomJsonString.left(mbomJsonString.length()-1);
    mbomJsonString.append("]");
    productInfo.mbom_src = mbomJsonString;
    insertProductionOrderToDatabase(productInfo);//Save production order info to database;
}

void MainWidget::insertProductionOrderToDatabase(ProductionVariant &productInfo)
{
    DataBaseQuery query(DataBase::getDataBase());
    DataBase::getDataBase().open();
    DataBase::getDataBase().transaction();
    QMap<QString,QVariant> map_Save;
    map_Save.insert(DBTab_ProductionOrder::_TAB_ORDER_TASK_ID,QVariant(productInfo.TaskId));
    map_Save.insert(DBTab_ProductionOrder::_TAB_ORDER_PRODUCT_NAME,QVariant(productInfo.ProductName));
    map_Save.insert(DBTab_ProductionOrder::_TAB_ORDER_PRODUCT_CODE,QVariant(productInfo.ProductCode));
    map_Save.insert(DBTab_ProductionOrder::_TAB_ORDER_MTYPE3,QVariant(productInfo.Mtype3));
    map_Save.insert(DBTab_ProductionOrder::_TAB_ORDER_DEVICE_TYPE,QVariant(productInfo.DeviceType));
    map_Save.insert(DBTab_ProductionOrder::_TAB_ORDER_ORDER_CODE,QVariant(productInfo.OrderCode));
    map_Save.insert(DBTab_ProductionOrder::_TAB_ORDER_WORK_NUM,QVariant(productInfo.WorkNum));
    map_Save.insert(DBTab_ProductionOrder::_TAB_ORDER_WORK_TIME,QVariant(productInfo.WorkTime));
    map_Save.insert(DBTab_ProductionOrder::_TAB_ORDER_MODULE_ID,QVariant(productInfo.ModuleId));
    map_Save.insert(DBTab_ProductionOrder::_TAB_ORDER_DEVICE_ID,QVariant(productInfo.DeviceId));
    map_Save.insert(DBTab_ProductionOrder::_TAB_ORDER_MBOM,QVariant(productInfo.mbom_src));
    map_Save.insert(DBTab_ProductionOrder::_TAB_ORDER_TOOLINGRATIO,QVariant(productInfo.ToolingRatio));
    map_Save.insert(DBTab_ProductionOrder::_TAB_ORDER_PROCESS_ID,QVariant(productInfo.ProcessId));
    map_Save.insert(DBTab_ProductionOrder::_ADD_TIME,QVariant(QDateTime::currentDateTime()));
    query.insert(DBTab_ProductionOrder::TAB_ORDER,map_Save);
    DataBase::getDataBase().commit();
    DataBase::getDataBase().close();
}

void MainWidget::showDefectiveNumTips()
{
    fullScreenModalDlg *defectiveNumTipsDialog = new fullScreenModalDlg(QString("不良品数偏差超过5个，\n请联系组长刷卡确认！"),this,false);
    defectiveNumTipsDialog->show();
    this->setFocus();
    m_deviceState->setDeviceStation(DeviceState::FIRST_CHECK_STATION);
    connect(this,SIGNAL(closeDefectiveTips()),defectiveNumTipsDialog,SLOT(reject()));
    connect(defectiveNumTipsDialog,SIGNAL(rejected()),this,SLOT(defectiveNumTipsCheckOK()));
}



void MainWidget::receiveHttpUserPermission(QString permission)
{
    QString station;
    m_deviceState->getDeviceStationString(station);
#ifdef QT_DEBUG
    //permission = "yes";
#endif
    if(m_currentStation.compare(station) == 0)
    {
        if(permission.compare("yes")==0)
        {
            if(m_deviceState->getDeviceStation() == DeviceState::MAINTAIN_STATION) {
                emit spotCheckPerrmisionOK();
                deleleMashWarningDialog();
            }
            else if(m_deviceState->getDeviceStation() == DeviceState::FIRST_CHECK_STATION) {
                emit closeFirstCheckDialog();
                emit closeDefectiveTips();
                emit sig_firstCheck();
                sendCloseInputDialogSignal_ByHeadMan();
            }
            else if(m_deviceState->getDeviceStation() == DeviceState::OPERATOR_WORK_STATION) {
                qDebug()<<"++++++OP_station";
                emit closeFirstProductionCheckDialog();
                emit opreatorCheckOK_signals();
                enableButton(true);
            }
            else if(m_deviceState->getDeviceStation() == DeviceState::QC_CHECK_STATION) {
                qDebug()<<"++++++QC_station";
                emit qcCheckPermissionOK();
                emit qcCHKPermissionOK();
                sendCloseConfirmDialogSignal_ByQcMan();
            }
        }
        else if(permission.compare("no")==0)
        {
            ProductionVariant productInfo;
            queryCurrentOrder(productInfo, getCurrentTaskId());
            QString strMCode1, strMCode2;
            QJsonParseError jsError;
            QJsonDocument jsDoc = QJsonDocument::fromJson(productInfo.mbom_src.toUtf8(), &jsError);
            if( jsError.error == QJsonParseError::NoError )
            {
                if( jsDoc.isArray())
                {
                    QJsonArray arr = jsDoc.array();
                    for( int i =0; i<arr.size(); ++i)
                    {
                        if(i == 0)
                            strMCode1 = arr[i].toObject()["MCode"].toString();
                        if(i == 1)
                            strMCode2 = arr[i].toObject()["MCode"].toString();
                    }
                }
            }
            MyMessageDialog::message(this,
                                     "警告！","当前操作无权限，请重新扫码！\nMCode应为:"
                                     + strMCode1+"\n"+ strMCode2 ,
                                     3000);
        }
    }
}

void MainWidget::receiveStation_fromHttp(QString station)
{
    m_currentStation = station;
}


void MainWidget::orderCompleted_slots()
{
    emit sig_orderCompleted();
    int mod = BasicSettingWidget::getOprtMode();
    if (mod == BasicSettingWidget::MASHWELDER_MODE){
        saveElectrodeCountToDataBase();//TODO 20180806 Add need test
    }
    m_deviceState->setMachineState(DeviceState::MACHINE_ORDER_COMPLETED);//string value is : completed
    QString deviceState;
    m_deviceState->getMachineStateString(deviceState);
    m_httpClient->putUpdateDevice(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"State",deviceState);
    m_deviceState->setOrderState("已完成");
    order_finished_flag = false;

    ProductionVariant productinfo;
    QString order_flag;
    queryCurrentOrder(productinfo,order_flag);

    /*--- Put订单状态 ----*/
    m_httpClient->postOrderState(m_deviceState->getOrderState(),m_deviceInfo->deviceType,m_deviceInfo->deviceId,productinfo.TaskId);
    DataBaseQuery query(DataBase::getDataBase());
    DataBase::getDataBase().open();
    DataBase::getDataBase().transaction();
    if (!m_currentTaskId.isEmpty()) {
        QString order_delete_option  = " tab_order.task_id =  ";
        order_delete_option += "\""+ m_currentTaskId +"\"";//TODO 20180731 need modify
        qDebug() << Q_FUNC_INFO <<"order_delete_option:" << order_delete_option;
        query.deleteItem(DBTab_ProductionOrder::TAB_ORDER,order_delete_option);
    }
    DataBase::getDataBase().commit();
    DataBase::getDataBase().close();
    /*-----------------------------------------------*/
    QString tips = "订单已生产完成！!";
    static MyMessageDialog *dialog = NULL;
    if (dialog == NULL) {
        dialog = new MyMessageDialog(tips,tr("提示!"),this,tr("否"),tr("确定"));
        dialog->hideCancelBtn();
    }
    if (dialog->exec() == QDialog::Accepted)
    {
        dialog = NULL;
        DataBase::getDataBase().open();
        DataBase::getDataBase().transaction();
        //recordScaleData_slots();//订单完成的时候，自动执行一次秤的数据存储 //TODO 20180730 add need test
        if( (order_flag.compare("") == 0)  && !order_finished_flag)
        {
            ProductionVariant productinfo_new;
            QString test;
            queryCurrentOrder(productinfo_new,test);  //TODO remove at 20180706
            m_deviceState->setOrderState("已接单");
            //TODO 20180716 Need add condition to jump the list ui
            if (!productinfo_new.TaskId.isEmpty() && !productinfo_new.ProductName.isEmpty()  && !productinfo_new.WorkNum.isEmpty())
            {
                showProductionOrder();
            }
            setOrderButtonDisabled();
            removeDefectNumEvent();
            setDefectValue();
            if (mod == BasicSettingWidget::MASHWELDER_MODE){
                clearWeldingCount();
            }
            if (mod == BasicSettingWidget::PLASTIC_MODE){
                clearPressingCount();
            }
            order_finished_flag = true;
        }
        DataBase::getDataBase().commit();
        DataBase::getDataBase().close();
    }
}

void MainWidget::clearPressingCount(){
    //do noting, need son class to do 2018 11/18 xuyifu
}
void MainWidget::clearWeldingCount()
{
    //do noting, need son class to do 2018 11/18 xuyifu
}

void MainWidget::firstProductionOK_toScanOperator()
{
    m_deviceState->setDeviceStation(DeviceState::FIRST_CHECK_STATION);
    /*----zhanglong*/
    MashWelder::m_systemStatus |= 0x4000;
    PunchingMachine::m_systemStatus |= 0x4000;
    PlasticPresses::m_systemStatus |= 0x4000;
    fullScreenModalDlg *firstProductionCheckDialog = new fullScreenModalDlg(QString("首件确认完成!\n请刷工卡以继续进行生产！"),this,false);
    firstProductionCheckDialog->show();
    //connect(this,SIGNAL(closeFirstProductionCheckDialog()),firstProductionCheckDialog,SLOT(reject()));
    connect(this,SIGNAL(closeFirstCheckDialog()),firstProductionCheckDialog,SLOT(reject()));
    connect(firstProductionCheckDialog,SIGNAL(rejected()),this,SLOT(firstProductCheckOK_Tips()));
}


void MainWidget::firstProductCheckOK_Tips()
{
    MyMessageDialog::message(0,"提示！","生产操作权限已确认，请继续生产～！",1500);
    /*----zhanglong*/
    MashWelder::m_systemStatus &= 0xbfff;
    PunchingMachine::m_systemStatus &= 0xbfff;
    PlasticPresses::m_systemStatus &= 0xbfff;
    _FirstCheckPass = true;
}

void MainWidget::firstQcCheck()
{

    /*----zhanglong*/
    MashWelder::m_systemStatus |= 0x4000;
    PunchingMachine::m_systemStatus |= 0x4000;
    PlasticPresses::m_systemStatus |= 0x4000;
    fullScreenModalDlg *firstQCCheckDialog = new fullScreenModalDlg(QString("QC确认完成!\n请刷工卡以继续进行生产！"),this,false);
    firstQCCheckDialog->show();
    m_deviceState->setDeviceStation(DeviceState::QC_CHECK_STATION);
    connect(this,SIGNAL(qcCheckPermissionOK()),firstQCCheckDialog,SLOT(reject()));
    connect(firstQCCheckDialog,SIGNAL(rejected()),this,SLOT(firstQCCheckPass_Tips()));
}

void MainWidget::showOrderCheckOK_Tips()
{
    emit showOrderTips();
}

void MainWidget::materialConfirm_slots()
{
    if(materialCheckDialog == NULL){
        materialCheckDialog = new fullScreenModalDlg(QString("请扫描物料二维码！"),this,false);
    }
    materialCheckDialog->show();
    m_deviceState->setDeviceStation(DeviceState::OPERATOR_WORK_STATION);
    connect(this,                   SIGNAL(materialConfirmOK()),    materialCheckDialog,    SLOT(accept()));
    connect(materialCheckDialog,    SIGNAL(accepted()),             this,                   SLOT(materialConfirmOK_slots()));
    m_materialBarcodeScanFlag = true;
}


void MainWidget::materialConfirmOK_slots()
{
    ProductionVariant p =  mParent->_productionVariant;
    if( p.ModuleId.isEmpty() == false)
    {
        Lock_Dlg dlg("请扫描工装模具！", this);
        connect( mParent, SIGNAL( sig_GongZhuangOk()), &dlg, SLOT(reject()) );
        dlg.exec();
    }

    materialCheckDialog = NULL;
    QString tips = "确认通过，请开始生产！";
    static MyMessageDialog *dialog = NULL;
    if(dialog == NULL) {
        dialog = new MyMessageDialog(tips,tr("物料确认"),this,tr("否"),tr("确定"));
        dialog->hideCancelBtn();
    }

    if(dialog->exec() == QDialog::Accepted)
    {
        dialog = NULL;
        emit startFirstProduction();
        emit hanjieguifanNum(p);
    }
}

void MainWidget::slot_hanjieguifanhao(ProductionVariant)
{

}

void MainWidget::qcCheckFun()
{
    if(m_deviceState->getQcCheckStatus() == QC_CHECKED_NG){
        if(m_qcCheck_circleAskTimer == NULL) {
            m_qcCheck_circleAskTimer = new QTimer(0);
        }
        m_qcCheck_circleAskTimer->start(60000*5);//5 minutes
        QTimer::singleShot( 60000*5, this, SLOT(qcCheckNG_AutoShowTips()) );
        //connect(m_qcCheck_circleAskTimer,SIGNAL(timeout()),this,SLOT(qcCheckNG_AutoShowTips()));
    }
    else {
        if(m_qc_checkTimer) {
            if(m_qc_checkTimer->isActive()) {
                m_qc_checkTimer->stop();
            }
        }
        if(m_qcCheck_circleAskTimer) {
            if(m_qcCheck_circleAskTimer->isActive()) {
                m_qcCheck_circleAskTimer->stop();
            }
        }
    }
}

//QC首检已确认
void MainWidget::firstQCCheckPass_Tips()
{
    /*----zhanglong*/
    _QCCheckPass = true;
    MyMessageDialog::message(0,"提示！","QC首检已确认，\n请继续生产～！",2000);
    MashWelder::m_systemStatus &= 0xbfff;
    PunchingMachine::m_systemStatus &= 0xbfff;
    PlasticPresses::m_systemStatus &= 0xbfff;
    MashWelder::QC_Scan_ckeck = false;
    PunchingMachine::QC_Scan_ckeck = false;
    PlasticPresses::QC_Scan_ckeck = false;
    m_deviceState->setQcCheckStatus(QC_CHECKED_PASS);
    setOrderButtonShow();
    if(m_qc_checkTimer) {
        if(m_qc_checkTimer->isActive()) {
            m_qc_checkTimer->stop();
        }
    }
    if(m_qcCheck_circleAskTimer) {
        if(m_qcCheck_circleAskTimer->isActive()) {
            m_qcCheck_circleAskTimer->stop();
        }
    }
}

void MainWidget::showDeviceFirstCheckTips()
{
    QString tips = "首检权限确认通过，请确认工单！";
    static MyMessageDialog *dialog = NULL;
    if(dialog == NULL) {
        dialog = new MyMessageDialog(tips,tr("首检权限"),this,tr("否"),tr("确定"));
        dialog->hideCancelBtn();
    }
    if(dialog->exec() == QDialog::Accepted)
    {
        dialog = NULL;
        emit enableOrderConfirm();
    }
}

void MainWidget::postOrder()
{    
    ProductionVariant productinfo;
    QString order_flag = "";
    queryCurrentOrder(productinfo,order_flag);
    //以POST方式，确认当前订单
    if (productinfo.TaskId.isEmpty() || productinfo.ProductName.isEmpty()\
            || productinfo.WorkNum.isEmpty()) {
        return;
    }
    m_httpClient->posDeviceInfo(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"TaskId",productinfo.TaskId);
    m_httpClient->posDeviceInfo(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"ProductName",productinfo.ProductName);
    m_httpClient->posDeviceInfo(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"WorkNum",productinfo.WorkNum);
}

void MainWidget::receiveHttpClientData(QByteArray str1, QByteArray str2)
{
    Q_UNUSED(str2);
    QString responseString = QString::fromUtf8(str1.data());
    qDebug() <<  str1;
    qDebug() << "9999999999999999999999999999999999999999";
    qDebug() << responseString;
    if( str1.isEmpty())
    {
        qDebug() << "9999999999999999999999999999999999999999";
    }

    if( str1.contains("ProcessId") )
    {
            qDebug() << "9999999999999999999999999999999999999999";
    }
    mHttpServer->response(responseString);
    QJsonParseError jsonErr;
    QJsonDocument myjsonDoc1 = QJsonDocument::fromJson(str1,&jsonErr);
    if(jsonErr.error == QJsonParseError::NoError)
    {
        if(!myjsonDoc1.isEmpty())
        {
            if(myjsonDoc1.isObject())
            {
                QJsonObject jobj = myjsonDoc1.object();
                QJsonObject::iterator it = jobj.begin();

                saveProductionVariant(jobj,tProductionInfo);

                ProductionVariant productinfo;
                QString order_flag;
                queryCurrentOrder(productinfo,order_flag);
                if (!productinfo.TaskId.isEmpty())
                {
                    m_deviceState->setOrderState("已接单");
                }

                if (!MashWelder::_orderBegin && !productinfo.TaskId.isEmpty() && !productinfo.ProductName.isEmpty() && !productinfo.WorkNum.isEmpty())
                {
                    qDebug() << Q_FUNC_INFO << "Product Order is not Empty";
                    showProductionOrder();
                }
                order_finished_flag = true;
                while (it != jobj.end()) {
                    switch (it.value().type()) {
                    case QJsonValue::String:
                    {
                        QString startcmd = it.value().toString();
                        Q_UNUSED(startcmd);
                    }
                        break;
                    default:
                        break;
                    }
                    it++;
                }
            }
        }
    }
}

void MainWidget::confirmCurrentOrderInfoByPostWay(ProductionVariant orderVariant)
{
    if (orderVariant.TaskId.isEmpty() ||\
            orderVariant.ProductName.isEmpty() ||\
            orderVariant.WorkNum.isEmpty() ||\
            orderVariant.ProductCode.isEmpty())
    {
        return;
    }
    m_deviceState->setOrderState("已接单");
    m_currentProductName = orderVariant.ProductName;
    m_currentWorkNum = orderVariant.WorkNum;
    m_currentWorkStartTime = orderVariant.OrderStartTime;
    m_currentTaskId = orderVariant.TaskId;
    setCurrentOrderStatusShow(orderVariant);
    m_httpClient->posDeviceInfo(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"TaskId",orderVariant.TaskId);
    m_httpClient->posDeviceInfo(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"ProductName",orderVariant.ProductName);
    m_httpClient->posDeviceInfo(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"WorkNum",orderVariant.WorkNum);
}

void MainWidget::returnFromProductOrderList()
{
    this->repaint();
    m_productListView->deleteLater();
    m_productListView = NULL;
}

void MainWidget::operatorCheckOk_Slots()
{

}

void MainWidget::defectiveNumTipsCheckOK()
{
    QString tips = tr("不良品数确认通过！");
    MyMessageDialog *dialog = new MyMessageDialog(tips,tr("提示!"),this,tr("否"),tr("确定"));
    dialog->hideCancelBtn();
    if(dialog->exec() == QDialog::Accepted)
    {
        m_deviceState->setDeviceStation(DeviceState::FIRST_CHECK_STATION);
        QTimer::singleShot(50,this,SLOT(orderCompleted_slots()));
    }
    slot_clearOrderMsg();
}

void MainWidget::slot_send7data()
{

}

void MainWidget::slot_clearOrderMsg()
{

}

void MainWidget::slot_sendOperator(QString, QString,  DeviceState::DeviceStion)
{

}


void MainWidget::slot_sendMaterial(QString, QString, QString)
{

}

void MainWidget::slot_sendGongZhang(QString, QString)
{

}


void MainWidget::initQCCheckDialog()
{
    if(m_qcCheckDialog == NULL) {
        initQCCheckDialogParama();
    }
    m_qcCheckDialog->setVisible(true);
    m_deviceState->setDeviceStation(DeviceState::QC_CHECK_STATION);
    connect(this,   SIGNAL(qcCHKPermissionOK()),    this,      SLOT(showQCCheckTips()));
}

void MainWidget::initSpotCheckEquipmentDialog()
{
    if(m_spotCheckDialog == NULL) {
        initSpotCheckDialogParama();
    }
    m_spotCheckDialog->setVisible(true);
    m_deviceState->setDeviceStation(DeviceState::MAINTAIN_STATION);
    connect(this,   SIGNAL(spotCheckPerrmisionOK()),    this,      SLOT(showDeviceCheckTips()));
}

void MainWidget::queryCurrentOrder(ProductionVariant &productinfo, QString currentTaskId)
{
    DataBaseQuery query(DataBase::getDataBase());
    DataBase::getDataBase().open();
    DataBase::getDataBase().transaction();
    QStringList keyList;
    keyList << DBTab_ProductionOrder::_TAB_ORDER_TASK_ID
            << DBTab_ProductionOrder::_TAB_ORDER_PRODUCT_NAME
            << DBTab_ProductionOrder::_TAB_ORDER_PRODUCT_CODE
            << DBTab_ProductionOrder::_TAB_ORDER_MTYPE3
            << DBTab_ProductionOrder::_TAB_ORDER_DEVICE_TYPE
            << DBTab_ProductionOrder::_TAB_ORDER_ORDER_CODE
            << DBTab_ProductionOrder::_TAB_ORDER_WORK_NUM
            << DBTab_ProductionOrder::_TAB_ORDER_WORK_TIME
            << DBTab_ProductionOrder::_TAB_ORDER_MODULE_ID
            << DBTab_ProductionOrder::_TAB_ORDER_DEVICE_ID
            << DBTab_ProductionOrder::_TAB_ORDER_MBOM
            << DBTab_ProductionOrder::_TAB_ORDER_PROCESS_ID
            << DBTab_ProductionOrder::_TAB_ORDER_TOOLINGRATIO;

    if (currentTaskId.isEmpty()){
        query.selectTable(DBTab_ProductionOrder::TAB_ORDER,&keyList,currentTaskId);
    }
    else {
        QString option = DBTab_ProductionOrder::_TAB_ORDER_TASK_ID + " = " + "\""+currentTaskId+"\"";
        query.selectTable(DBTab_ProductionOrder::TAB_ORDER,&keyList,option);
    }

    if(query.first()) {
        productinfo.TaskId = query.value(0).toString();
        productinfo.ProductName = query.value(1).toString();
        productinfo.ProductCode =  query.value(2).toString();
        productinfo.Mtype3 =  query.value(3).toString();
        productinfo.DeviceType =  query.value(4).toString();
        productinfo.OrderCode =  query.value(5).toString();
        productinfo.WorkNum =  query.value(6).toString();
        productinfo.WorkTime = query.value(7).toString();
        productinfo.ModuleId = query.value(8).toString();
        productinfo.DeviceId = query.value(9).toString();
        productinfo.mbom_src = query.value(10).toString();
        productinfo.ProcessId = query.value("ProcessId").toString();
        productinfo.ToolingRatio = query.value("ToolingRatio").toString();
    }
    DataBase::getDataBase().commit();
    DataBase::getDataBase().close();

}

DeviceInfo *MainWidget::getDeviceInfoObj()
{
    return m_deviceInfo;
}

HttpClient *MainWidget::getHttpClientObj()
{
    return m_httpClient;
}

DeviceState *MainWidget::getDeviceStateObj()
{
    return m_deviceState;
}

void MainWidget::confirmMateral()
{
    if(materialCheckDialog) {
        materialCheckDialog->accept();
    }
}

void MainWidget::initDevice()
{
    int mod = BasicSettingWidget::getOprtMode();
    switch (mod)   {
    case BasicSettingWidget::MASHWELDER_MODE:
        m_deviceInfo->deviceType = "点焊机";
        m_deviceInfo->deviceId = DeviceIdSettings::getDeviceId();
        break;
    case BasicSettingWidget::PLASTIC_MODE:
        m_deviceInfo->deviceType = "压塑机";
        m_deviceInfo->deviceId = DeviceIdSettings::getDeviceId();
        break;
    case BasicSettingWidget::PUNCHING_MODE:
        m_deviceInfo->deviceType = "冲压机";
        m_deviceInfo->deviceId = DeviceIdSettings::getDeviceId();
        break;
    default:
        break;
    }
}

void MainWidget::initSome()
{
    m_httpClient = HttpClient::getobj(m_deviceInfo->deviceType,m_deviceInfo->deviceId);
}

void MainWidget::initSpotCheckDialogParama()
{
    m_spotCheckDialog = new fullScreenModalDlg(QString("设备点检中......\n请设备维护人员刷卡确认！"),this,false);
    m_spotCheckDialog->setAttribute(Qt::WA_DeleteOnClose);
    m_spotCheckDialog->show();
}

void MainWidget::initQCCheckDialogParama()
{
    m_qcCheckDialog = new fullScreenModalDlg(QString("设备巡检中......\n请QC人员刷卡确认！"),this,false);
    m_qcCheckDialog->setAttribute(Qt::WA_DeleteOnClose);
    m_qcCheckDialog->show();
}
